﻿using UnityEngine;
using System.Collections;
using System.Threading;

public class WebCam : MonoBehaviour
{
    public static bool hasWebCam = false;
    private WebCamTexture webcamTexture = null;

    void Awake()
    {
        
    }

    public /*IEnumerator*/void InitCameraCor()
    {
        // 请求权限
        //yield return Application.RequestUserAuthorization(UserAuthorization.WebCam);

        float time = Time.time;
        if (/*Application.HasUserAuthorization(UserAuthorization.WebCam) && */WebCamTexture.devices.Length > 0)
        {
            //如果有后置摄像头，调用后置摄像头  
            for (int i = 0; i < WebCamTexture.devices.Length; i++)
            {
                if (!WebCamTexture.devices[i].isFrontFacing)
                {
                    webcamTexture = new WebCamTexture(WebCamTexture.devices[i].name, 480, 320);
                    hasWebCam = true;
                    break;
                }
            }
        }

        if (webcamTexture == null)
        {
            webcamTexture = new WebCamTexture(480, 320);
        }
        Renderer renderer = GetComponent<Renderer>();
        renderer.material.mainTexture = webcamTexture;
        time = Time.time - time;
        Debug.Log("WebCam Awake  " + time + "s");
    }

    // Use this for initialization  
    void Start()
    {
        InitCameraCor();

    }


    // Update is called once per frame
    void Update()
    {
        if (hasWebCam&& !webcamTexture.isPlaying)
        {
            //new Thread(() =>
            //{
            Debug.Log("ThreadWebCamStart");
            //Thread.Sleep(3000);
            webcamTexture.Play();
            hasWebCam = webcamTexture.isPlaying;
            Debug.Log("ThreadWebCamEnd");
            //}).Start(); 

        }
    }
}